//
//  StatusPictureView.swift
//  DSWeibo
//
//  Created by xiaomage on 15/9/13.
//  Copyright © 2015年 小码哥. All rights reserved.
//

import UIKit
import SDWebImage

protocol StatusPictureViewDelegate:NSObjectProtocol {
    func statusPictureView(pictureView:StatusPictureView ,didSelected:NSIndexPath,lagreUrl:[NSURL])
    
}

let PictureViewCellReuseIdentifier = "PictureViewCellReuseIdentifier"
class StatusPictureView: UICollectionView {
    
   weak var pictureViewDelegate:StatusPictureViewDelegate?

    
    var status: Status?
        {
        didSet{
            // 1. 刷新表格
            reloadData()
        }
    }
    
    private var pictureLayout: UICollectionViewFlowLayout =  UICollectionViewFlowLayout()
    init()
    {
        super.init(frame: CGRect.zero, collectionViewLayout: pictureLayout)
        
        // 1.注册cell
        register(PictureViewCell.self, forCellWithReuseIdentifier: PictureViewCellReuseIdentifier)
        self.isScrollEnabled = false
        // 2.设置数据源
        dataSource = self
        delegate = self
        
        // 2.设置cell之间的间隙
        pictureLayout.minimumInteritemSpacing = 10
        pictureLayout.minimumLineSpacing = 10
        
        // 3.设置配图的背景颜色
        backgroundColor = UIColor.white
    }

    
    /**
    计算配图的尺寸
    */
    func calculateImageSize() -> CGSize
    {
        // 1.取出配图个数
        let count = status?.storedPicURLS?.count
        // 2.如果没有配图zero
        if count == 0 || count == nil
        {
            return CGSize.zero
        }
        // 3.如果只有一张配图, 返回图片的实际大小
        if count == 1
        {
            // 3.1取出缓存的图片
            let key = status?.storedPicURLS!.first?.absoluteString
            let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: key!)
            
            // 3.2返回缓存图片的尺寸
            // 3.2返回缓存图片的尺寸
            guard image != nil else {
                pictureLayout.itemSize = CGSize.zero
                return CGSize.zero
            }
            pictureLayout.itemSize = image!.size
            return image!.size
        }
        // 4.如果有4张配图, 计算田字格的大小
        let margin = 10 * KTC_SCREEN_RATION
        if count == 4
        {
            let width = (UIScreen.main.bounds.size.width - margin-20*KTC_SCREEN_RATION) / 2.0
            pictureLayout.itemSize = CGSize(width: width, height: width)
            return CGSize(width: width, height: width)
        }
        
        // 5.如果是其它(多张), 计算九宫格的大小
        let width = (UIScreen.main.bounds.size.width - 2*margin-20*KTC_SCREEN_RATION) / 3.0
        pictureLayout.itemSize = CGSize(width: width, height: width)
        // 5.1计算列数
        let colNumber:CGFloat = 3
        // 5.2计算行数
        let rowNumber:CGFloat = CGFloat((count! - 1) / 3 + 1)
        // 宽度 = 列数 * 图片的宽度 + (列数 - 1) * 间隙
        let viewWidth = colNumber * width + (colNumber - 1) * margin
        // 高度 = 行数 * 图片的高度 + (行数 - 1) * 间隙
        let viewHeight = rowNumber * width + (rowNumber - 1) * margin
        return CGSize(width: viewWidth, height: viewHeight)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private class PictureViewCell: UICollectionViewCell {
        
        // 定义属性接收外界传入的数据
        var imageURL: NSURL?
            {
            didSet{
                iconImageView.sd_setImage(with: imageURL! as URL)
            }
        }
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            // 初始化UI
            setupUI()
        }
        
        private func setupUI()
        {
            // 1.添加子控件
            contentView.addSubview(iconImageView)
            // 2.布局子控件
            iconImageView.snp.makeConstraints { (make) -> Void in
                make.center.equalToSuperview()
                make.width.height.equalToSuperview()
            }
            
        }
        
        // MARK: - 懒加载
        private lazy var iconImageView:UIImageView = UIImageView()
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    
}


extension StatusPictureView: UICollectionViewDataSource
,UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        // 1.取出cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PictureViewCellReuseIdentifier, for: indexPath) as! PictureViewCell
        // 2.设置数据
        cell.imageURL = status?.storedPicURLS![indexPath.item]
        // 3.返回cell
        return cell

    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.storedPicURLS?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
//        print(status?.LargePictureURLS![indexPath.item])
        pictureViewDelegate?.statusPictureView(pictureView: self, didSelected: indexPath as NSIndexPath, lagreUrl: (status?.LargePictureURLS)!)
    }

    
    
    
}
